import { Component, Input, Output, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';

import { FileUploader, ParsedResponseHeaders, FileItem } from 'ng2-file-upload';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

import { ImageFile } from '../../model/file.model';


@Component({
  selector: 'app-file-uploader-multiple',
  templateUrl: './file.uploader.multiple.component.html',
  styleUrls: ['./file.uploader.multiple.component.css']
})
export class FileUploaderMultipleComponent implements OnInit, OnDestroy {

  uploader: FileUploader;
  @Input() accept = 'image/*';

  @Input() imageFiles: Array<ImageFile> = [];

  constructor(private sanitizer: DomSanitizer, public router: Router) { }

  ngOnInit() {
    this.uploader = new FileUploader({
      url: '/file/upload/image',
      method: 'POST',
      allowedFileType: ['image'],
      isHTML5: true,
      autoUpload: false,
      maxFileSize: 1024 * 1000,
    });
    // 绑定上传成功回调
    this.uploader.onSuccessItem = this.onSuccessItem.bind(this);
    this.uploader.onErrorItem = this.onErrorItem.bind(this);

  }

  ngOnDestroy() {
    this.uploader.destroy();
  }

  onSuccessItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any {
    let imageUrl = response;
    let imageFile = new ImageFile(null, imageUrl, item);
    this.imageFiles.push(imageFile);
  }

  onErrorItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any {
    if (status === 401) {
      this.router.navigate(['/login']);
    }
  }

  removeFileItem(item: FileItem, index: number) {
    if (item) {
      this.uploader.removeFromQueue(item);
    }
    this.imageFiles.splice(index, 1);
  }

  // 图片左移一位
  moveBackFileItem(index: number) {
    if (index > 0) {
      let temp = this.imageFiles[index];
      this.imageFiles[index] = this.imageFiles[index - 1];
      this.imageFiles[index - 1] = temp;
    }
  }

  // 图片由移一位
  moveForwardFileItem(index: number) {
    if (index < this.imageFiles.length - 1) {
      let temp = this.imageFiles[index];
      this.imageFiles[index] = this.imageFiles[index + 1];
      this.imageFiles[index + 1] = temp;
    }
  }

}



